package com.adong.onecoupon.merchant.admin.common.context;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Optional;

/**
 * 用户登录信息存储上下文
 */
public class UserContext {

    /**
     * <a href="https://github.com/alibaba/transmittable-thread-local" />
     */
    private static final ThreadLocal<UserInfoDTO> USER_INFO_DTO_THREAD_LOCAL = new TransmittableThreadLocal<>();


    /**
     * 设置用户上下文
     */
    public static void setUser(UserInfoDTO user) {
        USER_INFO_DTO_THREAD_LOCAL.set(user);
    }

    /**
     * 获取上下文用户名称
     * @return
     */
    public static String getUserId() {
        UserInfoDTO userInfoDTO = USER_INFO_DTO_THREAD_LOCAL.get();
        return Optional.ofNullable(userInfoDTO).map(UserInfoDTO::getUserName).orElse(null);
    }

    /**
     * 获取上下文中用户店铺编号
     * @return
     */
    public static Long getShopNumber() {
        UserInfoDTO userInfoDTO = USER_INFO_DTO_THREAD_LOCAL.get();
        return Optional.ofNullable(userInfoDTO).map(UserInfoDTO::getShopNumber).orElse(null);
    }

    /**
     * 清理用户上下文
     */
    public static void removeUser() {
        USER_INFO_DTO_THREAD_LOCAL.remove();
    }
}
